package com.learn.sc.springbootdemo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.learn.sc.springbootdemo.aop.DictParam;
import com.learn.sc.springbootdemo.mapper.ILoginMapper;
import com.learn.sc.springbootdemo.pojo.RetDataBean;
import com.learn.sc.springbootdemo.pojo.Users;
import com.learn.sc.springbootdemo.service.LoginService;
import com.learn.sc.springbootdemo.tools.SequenceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    private Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    ILoginMapper iLoginMapper;
    @Autowired
    SequenceManager sequenceManager;

    @Override
    @DictParam(dictKey = "SEX")
    public RetDataBean loginValidateInfo(Users user, RetDataBean retDataBean) {
        try {
            Users users= iLoginMapper.loginValidateInfo(user);
            if (!users.equals(null)){
                Map map = JSONObject.parseObject(JSONObject.toJSONString(users),Map.class);
                retDataBean.setRetCode("0");
                retDataBean.setRetMsg("登录成功");
                retDataBean.setRetData(map);
            }else {
                retDataBean.setRetCode("-1");
                retDataBean.setRetMsg("登录失败，账号或密码有误");
            }
        }catch (RuntimeException e){
            logger.error("登录验证异常:"+e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return retDataBean;
    }

    @Override
    @DictParam(dictKey = "SEX")
    public RetDataBean registerInfo(Users user, RetDataBean retDataBean) {
        try {
            Integer flag = iLoginMapper.acctExist(user.getUserAcct());
            if(flag.equals(1)){
                Map map = JSONObject.parseObject(JSONObject.toJSONString(user),Map.class);
                retDataBean.setRetCode("-1");
                retDataBean.setRetData(map);
                retDataBean.setRetMsg("账号已存在，请重试");
            }else{
                user.setUserId(sequenceManager.getSequenceByDate(SequenceManager.USER_ID));
                Integer updateRows = iLoginMapper.registerInfo(user);
                if(updateRows.equals(1)){
                    Map map = JSONObject.parseObject(JSONObject.toJSONString(user),Map.class);
                    retDataBean.setRetCode("0");
                    retDataBean.setRetData(map);
                    retDataBean.setRetMsg("注册成功");
                }else {
                    throw new Exception();
                }
            }
        }catch (Exception e){
            sequenceManager.decrSequence(SequenceManager.USER_ID);
            logger.error("注册异常:"+e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return retDataBean;
    }
}
